<?php
/**
 * 阿里云人脸比对1:1
 * 安装 alibabacloud/facebody-20191230
 */
use AlibabaCloud\SDK\Facebody\V20191230\Facebody;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Facebody\V20191230\Models\CompareFaceAdvanceRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use GuzzleHttp\Psr7\Stream;

class Face2 {

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Facebody Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/facebody
        $config->endpoint = "facebody.cn-shanghai.aliyuncs.com";
        return new Facebody($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function verify($filea,$fileb){
        // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $client = self::createClient('LTAI5tE6FUVonK1SJJJXH38S', '1IYnDjjQab4KZPVFZI6fUgWnP3Ma8i');

        $fileA = fopen($filea, 'rb');
        $streamA = new Stream($fileA);
        $fileB = fopen($fileb, 'rb');
        $streamB = new Stream($fileB);
        $compareFaceAdvanceRequest = new CompareFaceAdvanceRequest([
            "imageURLAObject" => $streamA,
            "imageURLBObject" => $streamB
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $resp = $client->compareFaceAdvance($compareFaceAdvanceRequest, $runtime);
            # 获取整体结果
            $response = $resp->body;
            if(isset($response->data)){
                $data = $response->data;
                if(isset($data->confidence)){
                    return ['code'=>1,'msg'=>'success','data'=>$data->confidence/100];
                }else{
                    return ['code'=>0,'msg'=>'验证失败'];
                }

            }else{
                //return ['code'=>0,'msg'=>$response['code'].':'.$response['desc']];
                return ['code'=>0,'msg'=>'验证失败'];
            }
        } catch (Exception $exception) {
            return ['code'=>0,'msg'=>'验证失败'];
            # 获取整体报错信息
            //return Utils::toJSONString($exception);
            # 获取单个字段
            //return $exception->getCode();
        }
    }
}
